package com.start.platform.core.event;

import com.start.common.tools.SpringContextTools;
import com.start.platform.core.entity.StartPlatformUserEntity;
import com.start.platform.core.vo.StartPlatformFansDetail;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Slf4j
public class GlobalStartPlatformUserEventDispatcher implements StartPlatformUserEvent {

    private static final GlobalStartPlatformUserEventDispatcher dispatcher = new GlobalStartPlatformUserEventDispatcher();
    private List<StartPlatformUserEvent> globalEvent;
    private volatile boolean isInit = false;

    public static GlobalStartPlatformUserEventDispatcher getInstance() {
        if (dispatcher.isInit) {
            return dispatcher;
        }
        synchronized (GlobalStartPlatformUserEventDispatcher.class) {
            if (dispatcher.isInit) {
                return dispatcher;
            }
            dispatcher.init();
            dispatcher.isInit = true;
        }
        return dispatcher;
    }

    private void init() {
        globalEvent = new ArrayList<>();
        Map<String, StartPlatformUserEvent> beans = SpringContextTools.getBeans(StartPlatformUserEvent.class, false);
        if (beans == null || beans.isEmpty()) return;
        Collection<StartPlatformUserEvent> values = beans.values();
        globalEvent = new ArrayList<>(values);


    }


    /**
     * 用户注册前
     *
     * @param user
     */
    @Override
    public void userRegisterBefore(StartPlatformFansDetail user) {
        if (globalEvent.isEmpty()) return;
        for (StartPlatformUserEvent event : globalEvent) {
            event.userRegisterBefore(user);
        }
    }

    /**
     * 用户注册后
     *
     * @param user
     */
    @Override
    public void userRegisterAfter(StartPlatformFansDetail user) {
        if (globalEvent.isEmpty()) return;
        for (StartPlatformUserEvent event : globalEvent) {
            event.userRegisterAfter(user);
        }
    }

    /**
     * 用户登录成功
     *
     * @param user
     */
    @Override
    public void userLoginAfter(StartPlatformUserEntity user) {
        if (globalEvent.isEmpty()) return;
        for (StartPlatformUserEvent event : globalEvent) {
            event.userLoginAfter(user);
        }
    }
}
